package com.zyy.seckill.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyy.seckill.entity.User;
import com.zyy.seckill.service.IUserService;
import com.zyy.seckill.utils.CookieUtil;
import com.zyy.seckill.vo.RespBean;
import com.zyy.seckill.vo.RespEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zyy
 * @DateTime: 2021/10/6 14:29
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    @Autowired
    IUserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    // 请求之前做处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) { // 判断是否为 handler
            User user = getUser(request, response);
            UserContext.setUser(user); // 把获取的user用户数据放在userContext中

            HandlerMethod hm = (HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null) { // 判断是否是使用 AccessLimit注解
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            String key = request.getRequestURI();
            if (needLogin) {
                if (user == null) {
                    render(response, RespEnum.SESSION_ERROR);
                    return false;
                }
            }
            key += ":" + user.getId();

            ValueOperations valueOperations = redisTemplate.opsForValue();
            Integer count = (Integer) valueOperations.get(key);
            if (count == null) {
                valueOperations.set(key, 1, seconds, TimeUnit.SECONDS);


            } else if (count < maxCount) {
                valueOperations.increment(key);
            } else {
                render(response, RespEnum.ACCESS_LIMIT);
                return false;
            }
        }
        return true;
    }

    /**
     * 处理拦截的请求返回错误信息
     *
     * @param response
     * @param sessionError
     */
    private void render(HttpServletResponse response, RespEnum sessionError) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        RespBean error = RespBean.error(sessionError);
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(error));
        writer.flush();
        writer.close();
    }

    /**
     * 获取当前登录用户 并且处理用户 user的数据
     *
     * @param request
     * @param response
     * @return
     */
    private User getUser(HttpServletRequest request, HttpServletResponse response) {
        String ticket = CookieUtil.getCookieValue(request, "userTicket");

        if (!StringUtils.hasLength(ticket)) {
            return null;
        }
        return userService.getUserByCookie(ticket, request, response);
    }
}
